package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.foolishbird.sdk.R;
import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.params.FloatGameServerResponseParams;
import com.foolishbird.sdk.params.RedResultResponseParams;
import com.foolishbird.sdk.params.ResponseParams;
import com.foolishbird.sdk.params.bean.FloatGameServer;
import com.foolishbird.sdk.params.bean.RedDetailInfo;
import com.foolishbird.sdk.params.bean.RedPackageInfo;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.utils.MyFragmentManger;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.WL;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.ArrayList;
import java.util.List;


public class RedpackageResultFragment extends BaseHttpFragment implements View.OnClickListener {

    private ImageView backView,backView2,avatarImage,typeImage;
    private TextView nameText,moneyText,infoText;
    private ListView mListview;
    private LinearLayout floatLayout;
    private View headView;

    private RedPackageInfo info;

    public static final RedpackageResultFragment newInstance(Bundle bundle) {
        RedpackageResultFragment fragment = new RedpackageResultFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "fb_redpackage_result");
        View contentView =inflater.inflate(resource,null);
        headView = inflater.inflate(ResUtils.getLayoutIdentifier(getActivity(), "fb_redpackage_result_head"),null);
        backView = headView.findViewById(getViewIdentifier("fb_fragment_login_back"));

        backView.setOnClickListener(this);
        avatarImage = headView.findViewById(getViewIdentifier("redpackage_result_avatar"));
        nameText = headView.findViewById(getViewIdentifier("foolishbird_avatar_name"));
        typeImage = headView.findViewById(getViewIdentifier("redpackage_result_type"));

        moneyText = headView.findViewById(getViewIdentifier("redpackage_result_money"));
        infoText = headView.findViewById(getViewIdentifier("redpackage_result_info"));
        floatLayout = contentView.findViewById(getViewIdentifier("redpackage_result_float"));
        backView2 = contentView.findViewById(getViewIdentifier("fb_fragment_login_back"));
        backView2.setOnClickListener(this);
        info = (RedPackageInfo)getArguments().getSerializable("info");
        typeImage.setVisibility(info.getIsLucky()==1?View.VISIBLE:View.GONE);
        if(!TextUtils.isEmpty(info.getAvatar())){
            Picasso.with(getContext()).load(info.getAvatar()).transform(new CircleTransform()).into(avatarImage);

        }
        nameText.setText(info.getNickName()+"的红包");
//        backView = contentView.findViewById(getViewIdentifier("redpackage_open_close"));
//        backView.setOnClickListener(this);
//        nameText = contentView.findViewById(getViewIdentifier("redpackage_open_name"));
//        openImage = contentView.findViewById(getViewIdentifier("redpackage_open_btn"));
//        openImage.setOnClickListener(this);
        mListview = contentView.findViewById(getViewIdentifier("float_notice_list"));
        mListview.addHeaderView(headView);
        mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (headView != null) {
                    int top = headView.getTop();
                    if(top<0){
                        floatLayout.setVisibility(View.VISIBLE);
                    }else {
                        floatLayout.setVisibility(View.GONE);
                    }
                }else{
                    floatLayout.setVisibility(View.GONE);
                }
//                if (i>=1){
//                    floatLayout.setVisibility(View.VISIBLE);
//                }else {
//                    floatLayout.setVisibility(View.GONE);
//                }
            }
        });
        HttpEngineApi.getInstance().redpackageInfo(info.getId(),requestCallbackHandler(RedResultResponseParams.class));
        return contentView;

    }

    private RedResultResponseParams.RedResultResponseData myNoticeList;

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (response != null) {
            int code = response.getState().getCode();
            if (State.SUCCESS == code) {
                if(response instanceof RedResultResponseParams){
                    myNoticeList =((RedResultResponseParams)response).getData();
                    setView();
                }
            }
        }
        WL.d("FloatNoticeFragment",response.toString());
    }

    private void setView(){
        moneyText.setText(myNoticeList.getMyUserMoney());
        infoText.setText(myNoticeList.getMaxCount()== myNoticeList.getReceivedCount()?
                myNoticeList.getMaxCount()+"个红包供"+myNoticeList.getAmount()+"元,"+myNoticeList.getFinish_the_time()+"被抢光"
        :"已领取"+myNoticeList.getReceivedCount()+"/"+myNoticeList.getMaxCount()+"个，共"+myNoticeList.getReceivedAmount()+"/"+myNoticeList.getAmount()+"元");
        mListview.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return myNoticeList.getRedPackageInfos()==null?0:myNoticeList.getRedPackageInfos().size();
            }

            @Override
            public Object getItem(int i) {
                return myNoticeList.getRedPackageInfos().get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                ViewHolder holder = null;
                if (view == null) {
                    int resource = ResUtils.getLayoutIdentifier(getContext(), "fb_redpackage_result_item");
                    view = LayoutInflater.from(getContext()).inflate(resource, null);
                    holder = new ViewHolder();
                    holder.avatar = view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_result_avatar"));
                    holder.nameText = view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_result_name"));
                    holder.timeText = view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_result_time"));
                    holder.moneyText = view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_result_money"));
                    holder.luckyText = view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_result_lucky"));
                    view.setTag(holder);
                }else {
                    holder = (ViewHolder) view.getTag();
                }

                RedPackageInfo  info = myNoticeList.getRedPackageInfos().get(i);
                Picasso.with(getContext()).load(info.getAvatar()).error(ResUtils.getDrawableIdentifier(getContext(),"foolishbird_avatar_default")).into(holder.avatar);
                holder.nameText.setText(info.getNickName());
                holder.timeText.setText(info.getCreated_at());
                holder.moneyText.setText(info.getAmount()+"元");
                holder.luckyText.setVisibility(info.getIsLucky()==1?View.VISIBLE:View.INVISIBLE);
                return view;
            }
        });

    }
    class ViewHolder {
        ImageView avatar;
        TextView nameText;
        TextView timeText;
        TextView moneyText;
        TextView luckyText;
    }

    @Override
    public void onClick(View view) {
        if(view ==backView){
            MyFragmentManger.getInstance().goBack(this);
        }else if(view ==backView2){
            MyFragmentManger.getInstance().goBack(this);
        }
//        else if(view==openImage){
//
//        }
//        OnFinishActivityListener listener = getOnFinishActivityListener();
//        if (listener != null) {
//            listener.doFinishActivity(this);
//        }
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }

    class CircleTransform implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {
            /**
             * 求出宽和高的哪个小
             */
            int  size = Math.min(source.getWidth(), source.getHeight());

            /**
             * 求中心点
             */
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;

            /**
             * 生成BitMap
             */
            Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
            if (squaredBitmap != source) {
                //释放
                source.recycle();
            }

            /**
             * 建立新的Bitmap
             */
            Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

            /**
             * 画布画笔
             */
            Canvas canvas = new Canvas(bitmap);
            Paint paint  = new Paint();

            BitmapShader shader = new BitmapShader(squaredBitmap,
                    BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
            paint.setShader(shader);
            paint.setAntiAlias(true);

            float r = size / 2f;
            /**
             * 画圆
             */
            canvas.drawCircle(r, r, r, paint);

            squaredBitmap.recycle();
            return bitmap;
        }

        @Override
        public String key() {
            return "circle";
        }
    }
}
